#include "infodownloader.h"

#include <QDebug>
#include <QUrl>
#include <QDateTime>
#include <QTimer>

InfoDownloader::InfoDownloader(QObject* parent) : QObject(parent), lyricsDownloader(0), infoDownloader(0), coverDownloader(0) {}

void InfoDownloader::startFetchingSongInfo() {
	if(!infoDownloader) {
		infoDownloader = new QNetworkAccessManager(this);
		connect(infoDownloader, SIGNAL(finished(QNetworkReply*)), this, SLOT(gotSongInfo(QNetworkReply*)));
		
		QUrl address("http://www2.radioparadise.com/now_playing.xml?nocache=1");
		infoDownloader->get(QNetworkRequest(address));
	}
}

void InfoDownloader::startFetchingLyrics() {
	if(!lyricsDownloader) {
		lyricsDownloader = new QNetworkAccessManager(this);
		connect(lyricsDownloader, SIGNAL(finished(QNetworkReply*)), this, SLOT(gotLyrics(QNetworkReply*)));
		
		QUrl lyricsUrl("http://lyricwiki.org/api.php");
		lyricsUrl.addQueryItem("fmt", "text");
		lyricsUrl.addQueryItem("artist", songInfo.artist);
		lyricsUrl.addQueryItem("song", songInfo.title);
		lyricsDownloader->get(QNetworkRequest(lyricsUrl));
	}
}

QString InfoDownloader::getElementText(QDomDocument& doc, const char* tagName) {
	QDomNodeList currNode = doc.elementsByTagName(tagName); 
	if(currNode.length() == 1 && currNode.at(0).isElement())
		return currNode.at(0).toElement().text().replace("\\", "");
	return QString();
}\

void InfoDownloader::gotSongInfo(QNetworkReply* reply) {
	bool error = reply->error() != QNetworkReply::NoError;
	QByteArray data = reply->readAll();

	if(!error) {
		QDomDocument doc; 
		if(doc.setContent(data)) {
			int diff = getElementText(doc, "refresh_time").toInt()-QDateTime::currentDateTime().toTime_t();
			if(diff > 0)
				QTimer::singleShot(diff*1000, this, SIGNAL(nextSongAvailable()));
			
			songInfo.songId = getElementText(doc, "songid").toInt();
			songInfo.title = getElementText(doc, "title");
			songInfo.artist = getElementText(doc, "artist");
			songInfo.album = getElementText(doc, "album");
			songInfo.amazonId = getElementText(doc, "asin");
		}
		emit(songInfoReady());
		
		qDebug() << "got amazon id of:" << songInfo.amazonId;
		if(!songInfo.amazonId.isEmpty() && !coverDownloader) {
			coverDownloader = new QNetworkAccessManager(this);
			connect(coverDownloader, SIGNAL(finished(QNetworkReply*)), this, SLOT(gotCover(QNetworkReply*)));
	
			QUrl address(QString("http://images.amazon.com/images/P/%1.01.MZZZZZZZ.jpg").arg(songInfo.amazonId)); // LZZZZZZZZ FOR A LARGE IMAGE
			coverDownloader->get(QNetworkRequest(address));
		}
		else // no amazon id, emit no cover signal
			emit(coverImageReady(QPixmap()));
	}
}

void InfoDownloader::gotCover(QNetworkReply* reply) {
	bool error = reply->error() != QNetworkReply::NoError;
	QByteArray imageData = reply->readAll();

	if(!error) {
		QPixmap coverImage;
		coverImage.loadFromData(imageData, "JPG");
		emit(coverImageReady(coverImage));
	}
}

void InfoDownloader::gotLyrics(QNetworkReply* reply) {
	bool error = reply->error() != QNetworkReply::NoError;
	QByteArray data = reply->readAll();

	if(error || data == "Not found") {
		qDebug() << "error fetching lyrics" << error;
		emit(lyricsReady("Could not find lyrics for "+songInfo.artist+" - "+songInfo.title));
		return;
	}
	emit(lyricsReady(QString::fromUtf8(data)));
}
